require 'yaml'
class Surveys::TSurveysController < ApplicationController
  layout "surveys/surveys"

  #before_filter :auth

  #protect_from_forgery :except => [:destroy_choice,:new_question,:pre_test,:prof_result,:record_zxs_yj]
  
  SurveyCountMethod.content_columns.each do |column|
    in_place_edit_for :survey_count_method, column.name
  end

  def index
    @surveys = Survey.t_surveys(20,params[:page])
    respond_to do |format|
      format.html
      format.xml {render :xml => @surveys.to_xml}
      format.json {render :json => @surveys.to_json}
    end
  end
  

  def new
    @survey = Survey.new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @survey }
    end
  end

  def create
    @survey = Survey.new(params[:survey])
    @survey.t_type = TEST_TYPE_TREND  #设置测试类型为倾向测试
    @survey.has_dimen = true #默认支持多维度

    if @survey.save
      flash[:notice] = '添加成功.'
      redirect_to(:action => "index")
    else
      render :action => "new"
    end
  end

  def edit
    @survey = Survey.find(params[:id])
    @question_num = @survey.question_num
  end



  def destroy
    @test = Survey.find(params[:id])
    @test.deleted = true
    @test.save
    respond_to do |format|
      format.html { redirect_to(:action => "index") }
    end
  end

  def update_info
    @survey = Survey.find(params[:id])

    if @survey.update_attributes(params[:survey])
      flash[:notice] = "保存成功。"
    end
    redirect_to :action => "edit", :id => @survey
  end

  def edit_info
    @survey = Survey.find(params[:id])
  end

  def new_type
    @types=SurveyType.find(:all)
  end
  
  def createnew_type
    @type=SurveyType.new(params[:type])
    if @type.save
       flash[:notice]="添加成功"
    end
    redirect_to(:action => "new_type" , :id=>1)
  end
  
  def edit_type
   @type=SurveyType.find(params[:id])
  end
 
  def update_type
     @type=SurveyType.find(params[:type_id])
    if @type.update_attributes(params[:type])
      flash[:notice]="修改成功"
    end
     redirect_to(:action => "new_type", :id => 1)
  end
  
  def del_dimen
   @dimen = Dimen.find(params[:id])
   @dimen.destroy
   respond_to do |format|
      format.html { redirect_to("/surveys/prof_surveys/"+@dimen.survey_id.to_s+"/edit") }
    end
  end
  
  def del_part
   @part = Part.find(params[:id])
   @part.destroy
   respond_to do |format|
      format.html { redirect_to("/surveys/prof_surveys/"+@part.survey_id.to_s+"/edit") }
    end
  end
  
  
  def destroy_type
   @type = SurveyType.find(params[:id])
   @type.destroy
   respond_to do |format|
      format.html { redirect_to(:action => "new_type",:id=>1) }
    end
  end



  def edit_test
    @test = Survey.find(params[:id])
  end

  def update_test
    @test = Survey.find(params[:id])

    if @test.update_attributes(params[:test])
      flash[:notice] = "保存成功。"
    end
    redirect_to :action => "edit_test", :id => @test
  end
  
  def new_part
    @test_id = params[:id]
    @part = Part.new
  end
  
  def create_part
    @test = Survey.find(params["test_id"].to_i)
    @test_id = @test.id
    @part = Part.new(params[:part])
    @part.survey = @test
    respond_to do |format|
      if @part.save
        flash[:notice] = '添加成功.'
        flash[:part_id] = @part.id
        format.html { redirect_to(:action => "edit", :id => @test.id) }
      else
        format.html { render :action => "new_part" }
      end
    end
  end

  def new_questions
    @part = Part.find(params[:id])
  end

  #编辑子量表
  def edit_part
    @part = Part.find(params[:id])
  end

  def update_part
    @part = Part.find(params[:id])

    if @part.update_attributes(params[:part])
      flash[:notice] = "保存成功。"
    end
    redirect_to :action => "edit_part", :id => @part
  end

  #添加题目
  def create_question
    @part = Part.find(params[:part_id])
    
    @question = Question.new(params[:question])
    @question.part = @part
    @question.survey = @part.survey
   # begin
     @question.save
      if params["choice.content"]
        i = 0;
          params["choice.content"].each do |content|
          choice = Choice.new(:content => content, :value => params["choice.value"][i])
          choice.question = @question
          choice.save
          i += 1
          end
       end
       flash[:q_error]=@question.errors[:number]
       @heighlight_id = @question.id
   
       respond_to do |format|
         format.html { render :partial => "questions"}
       end
        

  end
  
  #添加题目
  def create_question_by_test
    @test = Survey.find(params[:test_id])

    @question = Question.new(params[:question])
    @question.survey = @test
    @question.save

    if params["choice.content"]
      i = 0;
      params["choice.content"].each do |content|
        choice = Choice.new(:content => content, :value => params["choice.value"][i])
        choice.question = @question
        choice.save
        i += 1
      end
    end
    flash[:q_error]=@question.errors[:number]
    #设置高亮显示的元素
    @heighlight_id = @question.id

    respond_to do |format|
     format.html { render :partial => "questions_1"}
#      format.html { render :text => "questions_1"}
    end
  end
  
  #响应拖拽事件，排列quesiton的顺序
  def sort
    @part = Part.find(params[:id])

    @part.questions.each do |q|
      q.position = params['question-list'].index(q.id.to_s) + 1
      q.save!
    end

    #读取排列顺序后的questions
    @part.questions.sort {|a, b| b.position <=> a.position}

    render :noting => true
  end

  #响应拖拽事件，排列quesiton的顺序
  def sort_no_part
    @test = Survey.find(params[:id])

    @test.questions.each do |q|
      q.position = params['question-list'].index(q.id.to_s) + 1
      q.save!
    end

    #读取排列顺序后的questions
    @test.questions.sort {|a, b| b.position <=> a.position}

    render :noting => true
  end

  def new_dimen
    @test_id = params[:id]
    @dimen = Dimen.new
  end
  #添加维度
  def create_dimen
    @test = Survey.find(params["test_id"].to_i)
    @test_id = @test.id
    @dimen= Dimen.new(params[:dimen])
    @dimen.survey = @test
    respond_to do |format|
      if @dimen.save
        flash[:notice] = '添加成功.'
        flash[:dimen_id] = @dimen.id
        format.html { redirect_to(:action => "edit", :id => @test.id) }
      else
        format.html { render :action => "new_dimen" }
      end
    end
  end

  #定义计分方式
  def edit_count_method
    @test = Survey.find(params[:id])
    @survey_count_method =
      @test.survey_count_method == nil ? SurveyCountMethod.new : @test.survey_count_method
  end

  #添加计分方式
  def create_survey_count_method
    @survey_count_method = SurveyCountMethod.new(:add_num => params[:survey_count_method][:add_num])
    @test = Survey.find(params[:test_id])

    @survey_count_method.total = CountMethod.find(params[:survey_count_method][:total])
    @survey_count_method.avg = CountMethod.find(params[:survey_count_method][:avg])
    @survey_count_method.children_total = CountMethod.find(params[:survey_count_method][:children_total])
    @survey_count_method.children_avg= CountMethod.find(params[:survey_count_method][:children_total])
    @survey_count_method.dimen_total = CountMethod.find(params[:survey_count_method][:dimen_total])
    @survey_count_method.dimen_avg = CountMethod.find(params[:survey_count_method][:dimen_avg])

    @test.survey_count_method = @survey_count_method
    @test.save

    respond_to do |format|
      if @survey_count_method.save
        flash[:notice] = '添加成功.'
      else
        flash[:notice] = '添加失败.'
      end
      format.html { redirect_to(:action => "edit_count_method", :id => @test) }
    end
  end

  #定义常模
  def edit_norm
    @test = Survey.find(params[:id])
    @norm_info = @test.norm_info

    if @test.norm_info.norm_type == NORM_TYPE_TEXT
      render "new_norm"
    else
      @norms = Norm.cross_table(params[:id])

      @item_types = [
        [NOT_IMPORT, NOT_IMPORT],
        [NORM_ITEM_TYPE_PART, NORM_ITEM_TYPE_PART],
        [NORM_ITEM_TYPE_DIMEN, NORM_ITEM_TYPE_DIMEN]
      ]
    end
  end

  #根据item_type得到item列表
  def items_by_type
    test_id = params[:test_id]
    if params[:item_type] == NORM_ITEM_TYPE_NUM
      @items = []
    elsif params[:item_type] == NORM_ITEM_TYPE_PART
      @items = Part.find_all_by_test_id(test_id)
    elsif params[:item_type] == NORM_ITEM_TYPE_DIMEN
      @items = Dimen.find_all_by_test_id(test_id)

    end

    render :partial => "select"
  end

  def create_norm
    @test = Survey.find(params[:test_id])

    @norm = Norm.new(params[:norm])
    @norm.survey = @test
    @norm.explanation = "默认"

    @norm.save
    
    #设置高亮显示的元素
    @heighlight_id = @norm.id

    @norms = Norm.cross_table(params[:test_id])
    respond_to do |format|
      format.html { render :partial => "norms"}
    end
  end

  #添加文本常模
  def create_text_norm
    @test = Survey.find(params[:test_id])
    @norm_info = @test.norm_info
    @norm_info.description = params[:norm_info][:description]
    if @norm_info.save
      flash[:notice] = "常模保存成功"
      redirect_to :action => "edit", :id => @test
    else
      render "new_norm"
    end
  end

  #用iframe显示报告，这样的话页面的样式就不会被其他样式影响
  def _report
    @norm_info = NormInfo.find(params[:id])
    render :layout => false
  end


  def destroy_choice
     c_id=params[:id].split("$")[0]
     t_id=params[:id].split("$")[1]
     choice=Choice.find(c_id.to_i)
     choice.destroy
     respond_to do |format|
      format.html { redirect_to(:action => "new_question",:id=>t_id.to_i) }
    end
  end

  #测试完成，可以上线
  def finish
    @test = Survey.find(params[:id])
    @test.status = TEST_STATUS_FINISHED
    @test.save

    respond_to do |format|
      format.html { redirect_to(:action => "index") }
      format.xml  { head :ok }
    end
  end
  
  #量表停用
  def stop
    @test = Survey.find(params[:id])
    @test.status = TEST_STATUS_UNFINISHED
    @test.save
    respond_to do |format|
      format.html { redirect_to(:action => "index") }
      format.xml  { head :ok }
    end
  end

  def new_question
    @test = Survey.find(params[:id])
  end

  def new_norm_info
    @test_id = params[:id]
    @norm_info = NormInfo.new
  end

  def create_norm_info
    @test = Survey.find(params[:test_id])
    @norm_info = @test.norm_info
    @norm_info.description = params[:norm_info][:description]
    if @norm_info.save!
      flash[:notice] = "保存成功"
      redirect_to :action => "edit", :id => @test
    else
      render "new_norm_info"
    end
  end

 #预测试
  def pre_test
    @test = Survey.find(params[:id])
    if @test.t_type == TEST_TYPE_PROF
      if @test.has_part != 0
       @pages = @test.paging
#p @pages.to_s+"==========--------------------------========================="
        if @test.rg_method == "ruiwen"
          flash[:agenotice]="请准确填写被测者年龄，如：5岁填5，5岁半 填写5.5。每半岁一个年龄段。本量表适合于5到17岁"
        end
        render :template => "surveys/prof_surveys/prof_survey",:layout => false
      else
       @survey = @test.paging_no_part
        render :template => "surveys/prof_surveys/prof_survey_no_part",:layout => false
      end
    end
  end 
  
  
  def record_zxs_yj
    id=params[:record_id]
    @test_record = PreSurveyRecord.find(id)
    zxsyj=params[:report][:zxs_yj]
    @test_record.zxs_yj=zxsyj
    @test_zxs_yj=@test_record.zxs_yj
    p "=======#{id.to_s}====#{zxsyj}===="
    @test_record.save
    respond_to do |format|
      format.html { render :partial=>"zxs_yj"}
    end
  end
  
  
   def show_report

    @test=Survey.find(params[:id])
    @user = current_user
    # 清空 预测数据库表 
    PreSurveyRecord.delete_all
    PreOriginalResult.delete_all
    #username = params[:username].strip == "" ? "匿名" : params[:username]
    @test_record = PreSurveyRecord.new(:username => "匿名测试")
    @test_record.age=params[:age]
    @test_record.gender=params[:gender]
    @test_record.perfession=params[:perfession]
    @test_record.edu_status=params[:edu_status]
    @test_record.testname=@test.name
    @test_record.testtime=params[:timer]
    #@test_record.username = username 
    @test_record.survey_id = params[:id]
    @test_record.org = @user
    @test_record.save!

     params[:question_id].each do |q_id|
      #收集每道题的分值／记录原始分
      
      @or = PreOriginalResult.new
      @or.survey_id=params[:survey_id]
      @or.question_id = q_id
      @or.part_id = params["question-#{q_id}-part"].to_i if @test.has_part
      @or.value = Float(params["question-#{q_id}-value"])
      @or.choice_num = params["question-#{q_id}-choice"]
      @or.test_record_id = @test_record.id
      @or.save

    end
    #如果是独立的量表，就使用单独的报告生成策略
    rg_method=@test_record.survey.rg_method
    if rg_method && rg_method.length !=0 
      generate_report(@test_record.survey.rg_method)
    else
      do_report
      respond_to do |format|
        format.html { render :layout => false}
      end
    end
  end

  #导出为pdf
  def report_pdf
    @test_record = PreSurveyRecord.find(params[:id])
    do_report
    @dimens = []

    @dimen_results.each do |d|
      dim = Dimen.find(d.dimen.id)
      name = dim.name
      if  dim.formula and dim.formula.size > 0
        total = count_by_formula(d.total, Dimen.find(d.dimen.id).formula)
      else
        total = d.total
      end
      
      @dimens.push([name, total])
    end
    render :file => "/surveys/prof_surveys/report_pdf.prawn", :layout => false
  end

  def do_report
    #@test_record = PreSurveyRecord.find(params[:id])
    #统计分数
    
     @test_zxs_yj=@test_record.zxs_yj
    @total = PreOriginalResult.sum(:value, :conditions => ["test_record_id = ?", @test_record.id])
    @avg = PreOriginalResult.average(:value, :conditions => ["test_record_id = ?", @test_record.id])

    @original_results = PreOriginalResult.find_all_by_test_record_id(@test_record.id)

    @part_results = PreOriginalResult.find_by_sql(
      [ "select part_id, sum(value) total, avg(value) avg from pre_original_results
          where test_record_id = ? group by part_id", @test_record.id
      ]
    )

    @dimen_results = PreOriginalResult.find_by_sql(
      [ "select dimen_id, sum(value) total, avg(value) avg from
          (select question_id, value from pre_original_results where test_record_id = ?) t1,
          (select * from dimens_questions) t2
         where t1.question_id = t2.question_id group by dimen_id",
        @test_record.id
      ]
    )
  
    @norms = Norm.cross_table(@test_record.survey_id.to_s)
    @test = @test_record.survey
    #report_xml(@test_record.id)
    #PreOriginalResult.delete_all
    #PreSurveyRecord.delete_all
  end
  #维度图表 xml 
  def report_xml
    sql="select dimen_id, sum(value) total, avg(value) avg from
          (select question_id, value from pre_original_results where test_record_id = #{params[:id]}) t1,
          (select * from dimens_questions) t2
         where t1.question_id = t2.question_id group by dimen_id"
    @dimen_results = PreOriginalResult.find_by_sql(sql)

    headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8
    render :layout => false
  end
  #  分量表图表 xml 
  def part_report_xml
   sql="select part_id, sum(value) total, avg(value) avg from pre_original_results
          where test_record_id = #{params[:id]} group by part_id"
   @part_results = PreOriginalResult.find_by_sql(sql)

    headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8
    render :layout => false
  end
  
  def ept_report_xml
      sql="select dimen_id, sum(value) total, avg(value) avg from
                (select question_id, value from pre_original_results where test_record_id = #{params[:id]}) t1,
                (select * from dimens_questions) t2
               where t1.question_id = t2.question_id group by dimen_id"
      dimen_results = OriginalResult.find_by_sql(sql)
      test_record=SurveyRecord.find(params[:id])
      gender=test_record.gender
      @ept_drs=[]
     dimen_results.each do |dimen_r|
         item=[]
         if  dimen_r.total.to_i > 20
             dimen_r.total= 20
         end
         sql1="select * from ept_trans where original_mark = #{dimen_r.total}"
         t_result=EptTran.find_by_sql(sql1)
         if gender=="男"
             columnname=Dimen.find(dimen_r.dimen_id).name+"1".to_s
             dimen_r.total = t_result[0].send(columnname)
             item << dimen_r.dimen_id
             item << dimen_r.total
         else
            columnname=Dimen.find(dimen_r.dimen_id).name+"0".to_s
            dimen_r.total = t_result[0].send(columnname)
             item << dimen_r.dimen_id
             item << dimen_r.total
         end
         @ept_drs << item
       end
       headers["Content-Type"] = "text/xml; charset=utf-8"  # xml content with charset=uttf-8 
       render  :layout => false
  end
  
  
  #给测试增加图片
  def add_image_fortest
   @test=Survey.find(params[:id])
  end
  def create_image_fortest
      @image = Image.new(params[:image])
     @image.survey_id=params[:t_id]
     @image.filename=@image.filename
     if @image.save
         flash[:notice] = '图片添加成功'
         redirect_to(:action=>"index" )
     else
         redirect_to(:action=>"index" )
     end
  end

  def edit_dimen
    @dimen = Dimen.find(params[:id])
    @questions = @dimen.survey.questions
  end

  def update_dimen
    @dimen = Dimen.find(params[:id])

    if params[:dimen] == nil or params[:dimen][:question_ids] == nil
      params[:dimen] = Hash.new
      params[:dimen][:question_ids] = []
    end
    if @dimen.update_attributes(params[:dimen])
      flash[:notice] = "保存成功。"
    end
    redirect_to :action => "edit_dimen", :id => @dimen
  end

  def check
    @test = Survey.find(params[:id])
    if @test.norm_info.norm_type == NORM_TYPE_TEXT
      
    else
      
    end
  end

  def destroy_question

    @question = Question.find(params[:id])
    @part = @question.part 

    @question.delete
    @question.choices.delete_all

    @hide_id = @question.id

    respond_to do |format|
      format.html { render :partial => "questions"}
    end
  end

  def destroy_question_no_part

    @question = Question.find(params[:id])
    @test = @question.survey

    @question.delete
    @question.choices.delete_all

    @hide_id = @question.id

    respond_to do |format|
      format.html { render :partial => "questions_1"}
    end
  end

  def update_question
    @test = Survey.find(params[:test_id])
    @question_num = params[:question_num]
    @question = Question.find(params[:id])
    @question.number=params[:question_number]
    @question.can_ignore = params[:can_ignore]
    @question.description = params["description"]
    begin
      @question.save!
      params["choice_ids"].each do |id|
        choice = Choice.find(id)
        choice.content = params["choice#{id}"]["content"]
        choice.value = params["choice#{id}"]["value"]
        choice.save
      end
      respond_to do |format|
        format.html { render :partial => "question"}
      end
    rescue
      flash[:q_error]=@question.errors[:number]
      respond_to do |format|
        format.html { render :partial => "question"}
      end
    end
  end

  def explanations
     dimen_id=params[:id]
    @explanations=Explanation.find(:all, :conditions=> [ "dimen_id = ?", dimen_id])
  end

  def new_expl
    @explanation=Explanation.new
  end

  def create_expl
    @explanation=Explanation.new(params[:explanation])
    id=params[:explanation][:dimen_id]
    @explanation.save
    redirect_to(:action=>"explanations" ,:id=>id)
  end

 def del_expl
   explanation=Explanation.find_by_id(params[:id])
   d_id=explanation.dimen_id
   explanation.destroy
   respond_to do |format|
      format.html { redirect_to("/surveys/prof_surveys/explanations/#{d_id.to_s}")}
   end
 end
  
 #---------------------独立量表--------------------
  def generate_report(generate_method)
    send(generate_method)
  end

  def mmpi
    
    @report = CustomSurveys::Mmpi.pre_report(@test_record)
    #@t_xml = CustomSurveys::Mmpi.pre_t_xml(@report)
    @t_json = CustomSurveys::Mmpi.pre_t_json(@report)
pp @t_json
    respond_to do |format|
      format.html { render :template => "user/reports/custom/mmpi", :layout => "report"}
    end
  end


  def sixteen
    do_report
    @expls = CustomSurveys::Sixteen.expls(@dimen_results, @test_record.gender)
    render :template => "user/reports/custom/sixteen", :layout => "report"
  end

  def ept
    do_report
    gender=@test_record.gender
    if gender== nil 
        gender="男"
    end
    @ept_avg=@avg
    @ept_total=@total

     @dimen_results.each do |dimen_r|
     if  dimen_r.total.to_i> 20
         dimen_r.total= 20
     end
       sql="select * from ept_trans where original_mark = #{dimen_r.total}"
       t_result=EptTran.find_by_sql(sql)
       if gender=="男"
           columnname=Dimen.find(dimen_r.dimen_id).name+"1".to_s
           dimen_r.total = t_result[0].send(columnname)
       else
          columnname=Part.find(part_r.part_id).name+"0"
          dimen_r.total = t_result[0].send(columnname)
       end
     end
    render :layout => false
   end
   
   def ruiwen
    do_report
    #获取 被测者 年龄
    age= @test_record.age
    if age==nil ||age <5
        age=5
    elsif age >=17.1
        age=20
    end
    get_ruiwen_marks(age,@total)
    
    render   :template => "user/reports/custom/ruiwen" , :layout => false
   end
   def get_ruiwen_marks(age,tatol)
    #puts tatol.to_s+"======="
     data = YAML.load_file(RAILS_ROOT + "/db/yaml/ruiwen.yml")
     column_name="age"
     @index=6
     str=age.to_s
     str1=str.split(".")
       if str1.size >1
         column_name=column_name+str1[0]+str1[1]
       else
          column_name=column_name+str
       end
     #puts  data[send(#{column_name})]
     data_arr=data[:"#{column_name}"]
    for i in 1...data_arr.size
       if tatol >= data_arr[i]
           @index=i
           break
       end
    end
    
    def ruiwen_xml
        @score=params[:id]
    end
 #   puts @index.to_s+"-=-=-=-=-=-=-=-=-="+data_arr[@index].to_s
    @total_mark=data[:or_marks][@index];
  end

  #-----------------------------------------------
end
